package com.woniu.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.mapper.MenuMapper;
import com.woniu.pojo.Menu;
import com.woniu.pojo.dto.MenuDto;
import com.woniu.service.MenuService;
import com.woniu.until.ResponseData;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author whale
 * @description 针对表【menu】的数据库操作Service实现
 * @createDate 2023-11-01 15:52:50
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu>
        implements MenuService {

    @Override
    public ResponseData<?> queryUserMenu() {
        try {
            List<Menu> menus = this.list();

            List<MenuDto> menuDtoList = new ArrayList<>();

            for (Menu menu : menus) {
                MenuDto menuDto = new MenuDto();
                menuDto.setId(menu.getId());
                menuDto.setName(menu.getName());
                menuDto.setLink(menu.getLink());
                menuDto.setParentid(menu.getParentid());
                menuDto.setIcon(menu.getIcon());

                // 如果你有子菜单的逻辑，也需要处理子菜单的转换
                // 例如，menuDto.setChildrenMenu(convertMenuListToMenuDtoList(menu.getChildrenMenu()));

                menuDtoList.add(menuDto);
            }
            //先把父菜单全部过滤出来
            //每个父菜单都去找自己的子菜单,然后放入子菜单集合中
            List<MenuDto> parentMenu
                    = menuDtoList
                    .stream().filter(e -> e.getParentid() == null)
                    .collect(Collectors.toList());


            for (MenuDto parentmenu : parentMenu) {
                List<MenuDto> children = new ArrayList<>();
                for (MenuDto menuDto : menuDtoList) {
                    //通过父菜单的id等于菜单parentId条件找子菜单
                    if (parentmenu.getId().equals(menuDto.getParentid())) {
                        children.add(menuDto);
                    }
                }
                parentmenu.setChildrenMenu(children);
            }
            return new ResponseData<>().ok(parentMenu);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}




